package com.w4cms.controller.admin;

import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.w4cms.core.Consts;
import com.w4cms.interceptor.AdminInterceptor;
import com.w4cms.model.SysRole;
import com.w4cms.model.SysUser;
import com.w4cms.utils.Tools;
import com.w4cms.validator.LoginValidator;
@ControllerBind(controllerKey="/admin",viewPath="admin")
@Before(AdminInterceptor.class)
public class IndexController extends Controller {
	/**
	 * 登录页面
	 */
	@ClearInterceptor
	public void login(){
		render("login.html");
	}
	@ClearInterceptor
	public void logout(){
		removeSessionAttr(Consts.SESSION_USER);
		removeSessionAttr(Consts.SESSION_USER_NAME);
		removeSessionAttr(Consts.SESSION_ROLE_RIGHTS);
		removeSessionAttr(Consts.SESSION_USER_RIGHTS);
		if(!"index".equals(getPara("n"))){
			redirect("login.html");
		}else{
			redirect("../index.html");
		}
	}
	
	/**
	 *  登录验证
	 */
	@ClearInterceptor
	@Before(LoginValidator.class)
	public void sign_in(){
		String username = getPara("username");
		String password = getPara("password");
		if(Tools.isEmpty(username)||Tools.isEmpty(password)){
			setAttr("msg", "用户名或者密码为空");
			render("login.html");
			return;
		}
		SysUser user = SysUser.dao.login(username, password);
		if(user==null){
			setAttr("msg", "用户名或者密码错误");
			render("login.html");
			return;
		}else{
			setSessionAttr(Consts.SESSION_USER, user);
			setSessionAttr(Consts.SESSION_USER_NAME,user.get("username"));
			setSessionAttr(Consts.SESSION_USER_RIGHTS, user.get("rights"));
			SysRole role = user.getRole();
			if(role!=null){
				setSessionAttr(Consts.SESSION_ROLE_RIGHTS, role.get("rights"));
			}
			user.set("last_login", new Date()).update(); //更新最后一次登录时间
			redirect("index.html");
		}
		
	}
	public void index(){
		render("index.html");
	}
	public void welcome(){
		render("welcome.html");
	}
	public void user(){
		render("user.html");
	}
	public void menu(){
		render("menu.html");
	}
	public void category(){
		render("category.html");
	}
	public void article(){
		render("article.html");
	}
	public void topic(){
		render("topic.html");
	}
	public void setting(){
		render("setting.html");
	}
	public void banner(){
		render("banner.html");
	}
}
